package org.pb.org.service.impl;

import org.pb.basic.service.impl.BaseServiceImpl;
import org.pb.org.domain.Employee;
import org.pb.org.domain.Shop;
import org.pb.org.mapper.EmployeeMapper;
import org.pb.org.mapper.ShopMapper;
import org.pb.org.query.ShopQuery;
import org.pb.org.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 店铺的业务层接口实现类
 * @author
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop, ShopQuery> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    @Transactional
    public void remove(Long id) {
        if (id == null) {
            throw new RuntimeException("id不能为空");
        }
        // 先删除对应的管理员
        employeeMapper.removeByShop(id);
        // 再删除对应的店铺
        employeeMapper.remove(id);
    }

    @Override
    @Transactional
    public void batchRemove(List<Long> ids) {
        // 先删除对应的管理员
        employeeMapper.batchRemoveByShop(ids);
        // 再删除对应的店铺
        shopMapper.batchRemove(ids);
    }

    @Override
    @Transactional
    public void shopRegister(Shop shop) {
        if (shop == null) {
            throw new RuntimeException("店铺信息不能为空");
        }
        // 根据店铺名和店铺地址查询店铺的信息
        Shop dbShop = shopMapper.getByNameAndAddress(shop);
        // 如果获取到的店铺对象不为空，则表示已经有同一家店铺，则不能注册
        if (dbShop != null) {
            throw new RuntimeException("该店铺信息已经存在，请直接登陆。\n 如果忘记密码，请找回");
        }
        // 根据店铺管理员查询对应的员工信息
        Employee employee =  employeeMapper.loadByAccount(shop.getAdmin());
        // 如果店铺管理员信息存在，则表示该账号已经注册过一次店铺，不能重复注册店铺
        if (employee != null) {
            throw new RuntimeException("该账号已经注册了一次店铺，不能重复注册店铺！");
        }
        // 如果店铺不存在，则可以执行注册操作，首先进行店铺的管理员信息的注册，并获取到对应的自增长主键id
        employeeMapper.save(shop.getAdmin());
        // 此时shop对象中的admin已经有了对应的id值，可以通过该id完成admin_id的添加【sql中admin.id】
        shopMapper.save(shop);
        // 根据获取到的shop 的id，将对应的员工表的shop_id添加上
        Employee admin = shop.getAdmin();
        admin.setShop_id(shop.getId());
        employeeMapper.update(admin);
    }
}
